﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ActionSvc;
using CommonTools;
using Grpc.Core;
using Grpc.Net.Client;
using IncidentSvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace AggregationGateway.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SampleTestController : ControllerBase
    {
        private readonly ILogger logger;
        public SampleTestController(ILogger<SampleTestController> logger)
        {
            this.logger = logger;
        }

        [HttpGet("Test")]
        public string Test()
        {
            this.logger.LogInformation("ok");
            return "test.ok";
        }


        [HttpGet("GrpcTest")]
        public async Task<string> GrpcTest()
        {
            var client = new GrpcClient("http://localhost:5001");
            var response = await client.SendGrpcRequestAsync(g => new Greeter.GreeterClient(g), new HelloRequest { Name = "world" }, (x, y) =>
                  {
                      return x.SayHelloAsync(y);
                  }, ex =>
                   {
                       logger.LogError(ex, ex.Message);
                   });

            return $"GrpcTest.OK:{response.Message}";
        }


        [HttpGet("IncidentTest")]
        public async Task<string> IncidentTest()
        {
            //return await Task.FromResult("111");
            //var client = new GrpcClient("http://localhost:5001");
            //var response = await client.SendGrpcRequestAsync(g => new Greeter.GreeterClient(g), new HelloRequest { Name = "IncidentTest" }, (x, y) =>
            //{
            //    return x.SayHelloAsync(y);
            //}, ex =>
            // {
            //     logger.LogError(ex, ex.Message);
            // });

            //return $"IncidentTest.OK:{response.Message}";


            var channel = GrpcChannel.ForAddress("http://localhost:5001");
            var client = new Greeter.GreeterClient(channel);
            var response = await client.SayHelloAsync(new HelloRequest { Name = "IncidentTest" });

            return $"IncidentTest.OK:{response.Message}";
        }

        [HttpPost("GetIncidentList")]
        public async Task<string> GetIncidentList([FromForm] string incNos)
        {
            var client = new GrpcClient("http://localhost:5002");

            var response = await client.SendGrpcRequestAsync(g => new Incident.IncidentClient(g), new IncidentRequest { IncNos = incNos }, (x, y) =>
             {
                 return x.GetIncidentsAsync(y);
             });

            return response.Data;
        }
    }
}
